<template>
  <pro-provider :content-width="contentWidth">
    <a-layout :class="fullScreen ? 'without-layout' : 'ant-pro-basicLayout'">
      <template v-if="isMobile && !fullScreen">
        <a-drawer
          :body-style="{ padding: 0, height: '100%' }"
          placement="left"
          :width="sideWidth"
          :closable="false"
          :open="!collapsed"
          @update:open="updateCollapsed"
        >
          <sider-menu
            v-model:open-keys="openKeys"
            v-model:selected-keys="selectedKeys"
            style="height: 100%"
            :theme="theme"
            :layout="layout"
            :title="title"
            :fixed="fixedSidebar"
            :menus="menus"
            :sider-width="sideWidth"
            :split-menus="false"
            :collapsed-button="false"
            :collapsed="false"
          />
        </a-drawer>
      </template>
      <sider-menu
        v-else-if="!hasTopMenu && !fullScreen"
        v-model:collapsed="collapsed"
        v-model:open-keys="openKeys"
        v-model:selected-keys="selectedKeys"
        theme="light"
        :layout="layout"
        :title="title"
        :fixed="fixedSidebar"
        :menus="layout === 'mix' ? leftMenus : menus"
        :collected-menu-list="collectedMenuList"
        :split-menus="splitMenus"
        :collapsed-button="!splitMenus"
        @uncollectMenu="handleUncollectMenu($event)"
        @collectMenu="handleCollectMenu($event)"
      >
        <template v-slot:header>
          <a-input-search class="left-top-menu-search" placeholder="在此处搜索菜单" :allow-clear="!collapsed" @search="handleSearhMenu" />
        </template>
      </sider-menu>
      <a-layout>
        <header-view
          v-if="!fullScreen"
          v-model:collapsed="collapsed"
          v-model:open-keys="openKeys"
          v-model:selected-keys="selectedKeys"
          :theme="theme"
          :layout="layout"
          :title="title"
          :menus="menus"
          :collected-menu-list="collectedMenuList"
          :sider-width="sideWidth"
          :has-sider-menu="hasSideMenu"
          :fixed-header="fixedHeader"
          :split-menus="splitMenus"
          @uncollectMenu="handleUncollectMenu($event)"
          @collectMenu="handleCollectMenu($event)"
          @showSubMenu="showSubMenu"
        >
          <div style="text-align: right" class="flex items-center">
            <RightHeader />
            <console-icon />
            <setting-drawer />
            <!-- 由于涉密系统禁止点对点发消息，因此平台消息功能相关代码默认注释掉，项目上如有使用，请放开该代码 -->
            <notice-icon />
            <avatar-dropdown :current-user="currentUser" />
            <!-- <select-lang /> -->
          </div>
        </header-view>
        <multi-tab-vue v-if="multiTab" :fixed="multiTabFixed" :sider-width="sideWidth" />
        <router-view v-slot="{ Component }">
          <wrap-content>
            <component :is="Component" />
          </wrap-content>
        </router-view>
        <!-- <message-popup /> -->
      </a-layout>
    </a-layout>
  </pro-provider>
</template>

<script lang="ts">
import { defineComponent, computed, inject, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { genMenuInfoByKeywords, checkMenuTitleByKeywords } from './menu-util';
import { default as WrapContent } from '@/components/base-layouts/wrap-content/index.vue';
import { default as SiderMenu } from '@/components/base-layouts/sider-menu/index.vue';
import { default as HeaderView } from '@/components/base-layouts/header/index.vue';
// import { default as SelectLang } from '@/components/select-lang/index.vue';
import { default as AvatarDropdown } from '@/components/base-layouts/avatar-dropdown/index.vue';
import { default as SettingDrawer } from '@/components/setting-drawer/index.vue';
// 由于涉密系统禁止点对点发消息，因此平台消息功能相关代码默认注释掉，项目上如有使用，请放开该代码
import { default as NoticeIcon } from '@/components/notice-icon/index.vue';
// import { default as MessagePopup } from './components/message-popup/index.vue';
import { default as ConsoleIcon } from '@/components/base-layouts/console-icon/index.vue';
import type { MenuDataItem } from '@/router/typing';
import { MultiTab as MultiTabVue } from '@/components/multi-tab';
import { injectMenuState } from './use-menu-state';
import { useUserStore } from '@/store/user';
import { injectMultiTabStore } from '@/components/multi-tab/multi-tab-store';
import RightHeader from '@/extends/rightheader/index.vue';

export default defineComponent({
  name: 'BasicLayout',
  components: {
    MultiTabVue,
    WrapContent,
    SiderMenu,
    HeaderView,
    // SelectLang,
    // 由于涉密系统禁止点对点发消息，因此平台消息功能相关代码默认注释掉，项目上如有使用，请放开该代码
    NoticeIcon,
    // MessagePopup,
    AvatarDropdown,
    SettingDrawer,
    ConsoleIcon,
    RightHeader
  },
  setup() {
    const multiTabStore = injectMultiTabStore();
    const fullScreen = computed(() => {
      if (multiTabStore) {
        return multiTabStore.fullScreen;
      }
      return false;
    });
    const userStore = useUserStore();
    const { proxy } = getCurrentInstance();
    const { t } = useI18n();
    const menuState = injectMenuState();
    const isMobile = inject('isMobile', ref(false));
    const currentUser = computed(() => userStore.currentUser);
    const collectedMenuList = computed(() => {
      if (keywords.value) {
        return userStore.collectedMenuList.filter((item) => checkMenuTitleByKeywords(item.meta.title, keywords.value));
      }
      return userStore.collectedMenuList;
    });
    const hasSideMenu = computed(() => menuState.layout.value === 'side' || menuState.layout.value === 'left');
    const hasTopMenu = computed(() => menuState.layout.value === 'top');
    const keywords = ref('');
    // gen menus
    const allowRouters = computed(() => userStore.allowRouters); // genMenuInfo(filterMenu(routes)).menus;
    const menus = computed(() => {
      const keywordsForFirstMenu = menuState.layout.value === 'mix' ? '' : keywords.value;
      const menuList = genMenuInfoByKeywords(allowRouters.value, keywordsForFirstMenu, collectedMenuList.value);
      if (keywordsForFirstMenu.trim() && menuList.length !== 0) {
        menuList.forEach((i) => {
          menuState.openKeys.value.push(i.path);
        });
      }
      return menuList;
    });
    watch(
      () => menuState.layout.value,
      () => {
        keywords.value = '';
        loadSubMenus && loadSubMenus();
      }
    );
    /** 菜单搜索 */
    const handleSearhMenu = (value: string) => {
      if (menuState.collapsed.value) {
        menuState.collapsed.value = false;
      }
      keywords.value = value ? value.trim() : '';
    };
    /** 取消收藏菜单事件 */
    const handleUncollectMenu = (menuId) => {
      if (!menuId) return;
      userStore.UNCOLLECT_MENU(menuId);
      proxy.$message.success('取消收藏');
    };
    /** 收藏菜单事件 */
    const handleCollectMenu = (menu) => {
      if (!menu.meta?.id) return;
      userStore.COLLECT_MENU(menu as MenuDataItem);
      proxy.$message.success('收藏成功');
    };
    /** 简约主题(mix)左侧展示二级菜单 */
    const subMenus = ref([]);
    const showSubMenu = (children) => {
      subMenus.value = children || [];
    };
    const leftMenus = computed(() => {
      if ((menuState.selectedKeys.value.length && menuState.selectedKeys.value[0] === 'mixFav') || subMenus.value.length === 0) {
        const favMenus = genMenuInfoByKeywords(collectedMenuList.value, keywords.value, collectedMenuList.value);
        if (keywords.value.trim() && favMenus.length !== 0) {
          favMenus.forEach((i) => {
            menuState.openKeys.value.push(i.path);
          });
        }
        return favMenus;
      }
      const menuList = genMenuInfoByKeywords(subMenus.value, keywords.value, collectedMenuList.value);
      if (keywords.value.trim() && menuList.length !== 0) {
        menuList.forEach((i) => {
          menuState.openKeys.value.push(i.path);
        });
      }
      return menuList;
    });
    const loadSubMenus = () => {
      if (menuState.layout.value !== 'mix') return;
      const selectedKeys = menuState.selectedKeys.value || [];
      if (selectedKeys.length) {
        const { children } = menus.value.find((menu) => menu.path === selectedKeys[0]) || {};
        subMenus.value = children || [];
      }
    };
    onMounted(() => {
      /** 加载用户收藏的菜单 */
      userStore.GET_COLLECTED_MENUS();
      /** 加载简约主题的二级菜单 */
      loadSubMenus();
    });
    return {
      t,
      currentUser,
      menus,
      ...menuState,
      hasSideMenu,
      hasTopMenu,
      isMobile,
      collectedMenuList,
      handleSearhMenu,
      handleUncollectMenu,
      handleCollectMenu,
      fullScreen,
      subMenus,
      leftMenus,
      showSubMenu
    };
  }
});
</script>

<style lang="less">
body {
  @import '../components/base-layouts/basic-layout.less';
}
</style>
<style lang="less">
// 全屏不带导航样式
.ant-pro-admin-pro-water-mark-wrapper {
  height: 100%;
}
.without-layout {
  height: 100%;
  .ant-pro-multi-tab-wrap-fixed {
    width: 100% !important;
    top: 0px;
  }
  .ant-pro-basicLayout-content {
    height: 100%;
  }
}
</style>
